package com.ErpCoreWeb.Desktop;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CRole;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CDesktopApp;
import com.ErpCoreModel.UI.CDesktopAppMgr;
import com.ErpCoreModel.UI.CMenu;
import com.ErpCoreModel.UI.CRoleMenu;
import com.ErpCoreModel.UI.CUserMenu;
import com.ErpCoreModel.UI.CUserMenuMgr;
import com.ErpCoreModel.UI.CView;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class OrderMenu
 */
@WebServlet("/OrderMenu")
public class OrderMenu extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;
       
	public CUser m_User = null;

    public CView m_View = null;
    public UUID m_Catalog_id = Util.GetEmptyUUID();
    boolean m_bIsNew = false;
    public CUserMenuMgr m_UserMenuMgr = null;
    public CTable m_Table = null;
    public UUID m_guidCurGroupId = Util.GetEmptyUUID();
    public CCompany m_Company = null;
    public CDesktopAppMgr m_DesktopAppMgr = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrderMenu() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        CUser user = (CUser)request.getSession().getAttribute("User");
        m_UserMenuMgr = user.getUserMenuMgr();
        m_DesktopAppMgr = user.getDesktopAppMgr();
        m_Company = (CCompany)Global.GetCtx(this.getServletContext()).getCompanyMgr().Find(user.getB_Company_id());
        String GroupId = request.getParameter("GroupId");
        if (!Global.IsNullParameter(GroupId))
            m_guidCurGroupId = Util.GetUUID(GroupId);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
            GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
            PostData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
            Cancel();
            return ;
        }
	}

    void GetData()
    {
        List<CBaseObject> lstRet = new ArrayList<CBaseObject>();

        //用户菜单
        List<CBaseObject> lstObj = m_UserMenuMgr.GetList();
        for (int i = 0; i < lstObj.size(); i++)
        {
            CUserMenu UserMenu = (CUserMenu)lstObj.get(i);
            if (!UserMenu.getUI_DesktopGroup_id().equals(m_guidCurGroupId))
                continue;

            lstRet.add(UserMenu);
        }
        //角色菜单
        List<CBaseObject> lstObjR = m_Company.getRoleMgr().GetList();
        for (int i=0;i< lstObjR.size();i++)
        {
            CRole Role = (CRole)lstObjR.get(i);
            if (!((CUser)request.getSession().getAttribute("User")).IsRole(Role.getName()))
                continue;
            List<CBaseObject> lstObjRM = Role.getRoleMenuMgr().GetList();
            for (int j=0;j< lstObjRM.size();j++)
            {
                CRoleMenu RoleMenu = (CRoleMenu)lstObjRM.get(j);
                if (!RoleMenu.getUI_DesktopGroup_id().equals( m_guidCurGroupId))
                    continue;

                lstRet.add(RoleMenu);
            }
        }
        //桌面应用
        lstObj = m_DesktopAppMgr.GetList();
        for (int i = 0; i < lstObj.size(); i++)
        {
            CDesktopApp App = (CDesktopApp)lstObj.get(i);
            if (!App.getUI_DesktopGroup_id().equals(m_guidCurGroupId))
                continue;

            lstRet.add(App);
        }

        List<CBaseObject> lstObj1 =lstRet;
     // 排序,通过泛型和匿名类来实现  
        Collections.sort(lstObj1, new Comparator<CBaseObject>() {  
            public int compare(CBaseObject o1, CBaseObject o2) {  
                int result = GetIdx(o1) - GetIdx(o2);  
                return result;  
            }  
	       	 int GetIdx(CBaseObject obj)
	    	 {
	    		 if(obj.m_arrNewVal.containsKey("idx"))
	    			 return obj.m_arrNewVal.get("idx").IntVal;
	    		 return 0;
	    	 }
        }); 


        String sData = "";

        int iCount = 0;
        for (int i=0;i<lstObj1.size();i++)
        {
        	CBaseObject civ =lstObj1.get(i);
            //CColumn col = (CColumn)m_Table.ColumnMgr.Find(civ.FW_Column_id);
            //if (col == null)
            //    continue;
            if (civ instanceof CUserMenu)
            {
                CUserMenu UserMenu = (CUserMenu)civ;
                CMenu menu = (CMenu)Global.GetCtx(this.getServletContext()).getMenuMgr().Find(UserMenu.getUI_Menu_id());
                sData += String.format("{ \"id\": \"%s\",\"ColName\":\"%s\"},", menu.getId().toString(), menu.getName());

                iCount++;
            }
            else if (civ instanceof CRoleMenu)
            {
                CRoleMenu RoleMenu = (CRoleMenu)civ;
                CMenu menu = (CMenu)Global.GetCtx(this.getServletContext()).getMenuMgr().Find(RoleMenu.getUI_Menu_id());

                sData += String.format("{ \"id\": \"%s\",\"ColName\":\"%s\"},", menu.getId().toString(), menu.getName());

                iCount++;
            }
            else if (civ instanceof CDesktopApp)
            {
                CDesktopApp App = (CDesktopApp)civ;
                sData += String.format("{ \"id\": \"%s\",\"ColName\":\"%s\"},", App.getId().toString(), App.getName());
                iCount++;
            }
         }
        if(sData.length()>0 && sData.endsWith(","))
        	sData = sData.substring(0, sData.length()-1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
             , sData, iCount);

		try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void PostData()
    {

        List<CBaseObject> lstRet = new ArrayList<CBaseObject>();

        //用户菜单
        List<CBaseObject> lstObj = m_UserMenuMgr.GetList();
        for (int i = 0; i < lstObj.size(); i++)
        {
            CUserMenu UserMenu = (CUserMenu)lstObj.get(i);
            if (!UserMenu.getUI_DesktopGroup_id().equals(m_guidCurGroupId))
                continue;

            lstRet.add(UserMenu);
        }
        //角色菜单
        List<CBaseObject> lstObjR = m_Company.getRoleMgr().GetList();
        for (int i=0;i< lstObjR.size();i++)
        {
            CRole Role = (CRole)lstObjR.get(i);
            if (!((CUser)request.getSession().getAttribute("User")).IsRole(Role.getName()))
                continue;
            List<CBaseObject> lstObjRM = Role.getRoleMenuMgr().GetList();
            for (int j=0;j< lstObjRM.size();j++)
            {
                CRoleMenu RoleMenu = (CRoleMenu)lstObjRM.get(j);
                if (!RoleMenu.getUI_DesktopGroup_id().equals(m_guidCurGroupId))
                    continue;

                lstRet.add(RoleMenu);
            }
        }
        //桌面应用
        lstObj = m_DesktopAppMgr.GetList();
        for (int i = 0; i < lstObj.size(); i++)
        {
            CDesktopApp App = (CDesktopApp)lstObj.get(i);
            if (!App.getUI_DesktopGroup_id().equals(m_guidCurGroupId))
                continue;

            lstRet.add(App);
        }

        List<CBaseObject> lstObj1 =lstRet;
     // 排序,通过泛型和匿名类来实现  
        Collections.sort(lstObj1, new Comparator<CBaseObject>() {  
            public int compare(CBaseObject o1, CBaseObject o2) {  
                int result = GetIdx(o1) - GetIdx(o2);  
                return result;  
            }   
	       	 int GetIdx(CBaseObject obj)
	    	 {
	    		 if(obj.m_arrNewVal.containsKey("idx"))
	    			 return obj.m_arrNewVal.get("idx").IntVal;
	    		 return 0;
	    	 }
        }); 


        String GridData = request.getParameter("GridData");
        if (GridData==null || GridData.isEmpty())
        {
            try {
				response.getWriter().print("字段不能空！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }

        String[] arr1 = GridData.split(";");
        for (int i = 0; i < arr1.length; i++)
        {
            String[] arr2 = arr1[i].split(":");
            //CMenu menu = (CMenu)m_UserMenuMgr.Find(new Guid(arr2[0]));

            for (int j=0;j< lstObj1.size();j++)
            {
            	CBaseObject civ=lstObj1.get(j);
                if ( civ instanceof CUserMenu)
                {
                    CUserMenu UserMenu = (CUserMenu)civ;
                    if (UserMenu.getUI_Menu_id().equals(Util.GetUUID(arr2[0])))
                    {
                        UserMenu.setIdx( i + 1);
                        m_UserMenuMgr.Update(UserMenu);
                        if (m_UserMenuMgr.Save(true))
                        {

                        }
                    }
                }
                else if (civ instanceof CRoleMenu)
                {
                    CRoleMenu RoleMenu = (CRoleMenu)civ;
                    if (RoleMenu.getUI_Menu_id().equals(Util.GetUUID(arr2[0])))
                    {
                        RoleMenu.setIdx(i + 1);
                        RoleMenu.m_ObjectMgr.Update(RoleMenu);
                        if (RoleMenu.m_ObjectMgr.Save(true))
                        { }
                    }
                }
                else if (civ instanceof CDesktopApp)
                {
                    CDesktopApp App = (CDesktopApp)civ;
                    if (App.getId().equals(Util.GetUUID(arr2[0])))
                    {
                        App.setIdx(i + 1);
                        m_DesktopAppMgr.Update(App);
                        if (m_DesktopAppMgr.Save(true))
                        { }
                    }
                }

            }

           // CUserMenu menu = (CUserMenu).GetCtx(Session["TopCompany"].ToString()).UserMenuMgr.Find(new Guid(arr2[0]));
           //// CMenu menu = (CMenu)Global.GetCtx(Session["TopCompany"].ToString()).MenuMgr.Find(new Guid(arr2[0]));
           // //CColumnInView civ = (CColumnInView)m_View.ColumnInViewMgr.Find(new Guid(arr2[0]));
           // //civ.Caption = arr2[1];
           // menu.Idx = i;
           // (CUserMenu).GetCtx(Session["TopCompany"].ToString()).UserMenuMgr.Update(menu);
           // m_View.ColumnInViewMgr.Update(menu);
        }
    }
    void Cancel()
    {
    	request.getSession().setAttribute("NewView", null);
    }
    
}
